/**
 * gf
 * 货币政策编辑组件
 */

import LittleTitle from "@/components/Title/littleTitle";
import { Input } from "antd";
import { Fragment, useEffect, useState } from "react";
import styles from "./index.less";
import * as cn from "classnames";
import styled from "styled-components";
import icon_plus from "@/assets/icons/icon-comment-add.png";
import icon_delete from "@/assets/icons/icon_delete.png";
import icon_delete_2 from "@/assets/icons/icon-delete-2.png";
import ButtonNoBorder from "@/components/Button/buttonNoBorder";
import { VerticleBar } from ".";
import { TableOptBtn } from "@/components/Button";
import TextEditor from "@/components/TinyEditor";
import { IconDelete } from "@/components/Icon";
import * as _ from "lodash";
import ErrorModal from "@/components/CommonComponents/ErrorModals";

const FlexDiv = styled.div`
  width: 100%;
  height: 28px;
  line-height: 28px;
  display: inline-flex;
  justify-content: space-between;
  align-items: center;
`;

const SecTitle = styled.div`
  position: relative;
  top: 4px;
  opacity: 0.7;
  font-weight: 600;
  margin-right: 8px;
  color: #35425e;
`;

interface MonetaryEditorTextProps {
  // editType: string;
  // editTitle: string;
  // callback: (type: string, val: string) => void;
  // editContent?: string;
  height?: number;
  monetaryReportData: any[];
  setMonetaryReportData: any;
  monetarySecReportData: any;
  setMonetarySecReportData: any;
  repeatFirName?: string[];
  repeatSecName?: any[];
  setRepeatFirName?: any;
  setRepeatSecName?: any;
  requiredFir?: string[];
  setRequiredFir?: any;
  // hasSider?: boolean;
  // checkFlag?: string;
  // broker?: string;
  // isSubmit?: boolean; // 多空判断必填判断
}

interface SecMonetaryEditorTextProps {
  editType: string;
  // editTitle: string;
  callback: (firkey: string, type: string, val: string, key?: string) => void;
  editContent?: string;
  height: number;
  firKey: string;
  setDeleteInfo: (v: any) => void;
  twoLevelCategory: string;
  repeatSecName?: any[];
  // hasSider?: boolean;
  // checkFlag?: string;
  // broker?: string;
  // isSubmit?: boolean; // 多空判断必填判断
}

const defaultObj: { firLevelName: string; key: string } = {
  firLevelName: "",
  key: "",
};

const MoSecEditorText = (secprops: SecMonetaryEditorTextProps) => {
  const {
    editType,
    editContent,
    height = 150,
    firKey,
    callback,
    setDeleteInfo,
    twoLevelCategory,
    repeatSecName,
  } = secprops;
  console.log(repeatSecName);

  return (
    <div className={styles.monetarySecBox}>
      <SecTitle>二级类别</SecTitle>
      <div style={{ flexGrow: 1 }}>
        <FlexDiv style={{ marginBottom: 8 }}>
          <div style={{ display: "inline-flex" }}>
            <Input
              placeholder="请输入二级分类名"
              className={cn(
                styles.header_titleInput,
                styles.select236,
                repeatSecName[firKey]?.includes(twoLevelCategory) &&
                  "form_error"
              )}
              maxLength={50}
              onChange={(e) =>
                callback(firKey, editType, e.target.value, "twoLevelCategory")
              }
              value={twoLevelCategory}
            />
            {repeatSecName[firKey]?.includes(twoLevelCategory) && (
              <span className={styles.errormsg}>
                该二级类别名称已有记录，不能重复，请确认！
              </span>
            )}
          </div>
          <IconDelete
            onClick={() => {
              setDeleteInfo({
                modalVisible: true,
                errorMsg: "确认要删除该二级分类？",
                firKey: firKey,
                secKey: editType,
              });
            }}
          />
        </FlexDiv>
        <TextEditor
          editorKey={"monetary_" + editType}
          content={editContent}
          onContentChange={(e) => {
            callback(firKey, editType, e, "content");
          }}
          onChangePureText={(e) => {
            callback(firKey, editType, e, "content" + "Str");
          }}
          height={height}
          simToolBar={"bold italic underline forecolor"}
          paste_as_text={true}
        />
      </div>
    </div>
  );
};

const MonetaryEditorText = (props: MonetaryEditorTextProps) => {
  const [errorList, setErrorList] = useState([]);
  const {
    monetaryReportData,
    monetarySecReportData,
    setMonetaryReportData,
    setMonetarySecReportData,
    repeatFirName,
    repeatSecName,
    setRepeatFirName,
    setRepeatSecName,
    requiredFir,
    setRequiredFir,
    setVisibleDeleteModal
  } = props;

  const [deleteInfo, setDeleteInfo] = useState<any>({
    modalVisible: false,
    errorMsg: "",
    firKey: "",
    secKey: "",
  });

  useEffect(() => {
    setVisibleDeleteModal(deleteInfo.modalVisible)
  }, [deleteInfo.modalVisible]);

  console.log(monetaryReportData, monetarySecReportData, requiredFir);

  // 添加一级分类
  const handleAddFirLevel = () => {
    if (monetaryReportData?.length > 0) {
      defaultObj.key =
        Number(monetaryReportData[monetaryReportData.length - 1].key) + 1 + "";
    } else {
      defaultObj.key = "0";
    }
    monetaryReportData.push(defaultObj);
    setMonetarySecReportData((state) => {
      return {
        ...state,
        [defaultObj.key]: [
          {
            key: defaultObj.key + "_" + 0,
          },
        ],
      };
    });
    setMonetaryReportData(_.cloneDeep(monetaryReportData));
  };

  // 删除分类
  const handleDeleteLevel = () => {
    if (deleteInfo.secKey) {
      // 删除二级分类
      handleDeleteSecLevel(deleteInfo.firKey, deleteInfo.secKey);
    } else {
      handleDeleteFirLevel(deleteInfo.firKey);
    }
    setDeleteInfo({
      modalVisible: false,
      errorMsg: "",
    });
  };

  // 删除一级分类
  const handleDeleteFirLevel = (key: string) => {
    const i = monetaryReportData.findIndex((v) => v.key == key);
    if (i > -1) {
      monetaryReportData.splice(i, 1);
    }
    if (monetarySecReportData[key]) {
      // 删除一级分类下的所有二级分类
      setMonetarySecReportData((state) => {
        return {
          ...state,
          [key]: [],
        };
      });
    }
    setMonetaryReportData(_.cloneDeep(monetaryReportData));
  };

  // 添加二级分类
  const handleAddSecLevel = (key: string) => {
    let tar = monetarySecReportData[key];
    if (tar && tar?.length > 0) {
      const max = Number(tar[tar.length-1].key.split('_')[1]) + 1
      tar.push({
        key: key + "_" + max,
      });
    } else {
      tar = [
        {
          key: key + "_" + 0,
        },
      ];
    }
    setMonetarySecReportData((state) => {
      return {
        ...state,
        [key]: tar,
      };
    });
  };

  // 删除二级分类
  const handleDeleteSecLevel = (firKey: string, secKey: string) => {
    const tar = monetarySecReportData[firKey];
    if (tar) {
      const i = tar.findIndex((m) => m.key == secKey);
      if (i > -1) {
        tar.splice(i, 1);
        setMonetarySecReportData((state) => {
          return {
            ...state,
            [firKey]: tar,
          };
        });
      }
    }
  };

  // 保存编辑的值
  /**
   *
   * @param firKey 一级key
   * @param secKey 二级key
   * @param content 值
   * @param key 字段
   */
  const handleSaveParams = (
    firKey: string,
    secKey: string,
    content: string,
    key?: string
  ) => {
    console.log(content, firKey, secKey, key);

    const i = monetaryReportData.findIndex((v) => v.key == firKey);
    if (secKey) {
      // 修改二级分类内容
      const j = monetarySecReportData[firKey].findIndex(
        (v) => v.key === secKey
      );
      if (j > -1) {
        const tar = monetarySecReportData[firKey][j];
        tar[key] = content;
        setMonetarySecReportData((state) => {
          return {
            ...state,
            [firKey]: monetarySecReportData[firKey],
          };
        });
      }
    } else {
      monetaryReportData[i].oneLevelCategory = content;
      setMonetaryReportData(_.cloneDeep(monetaryReportData));
    }
  };

  console.log(monetaryReportData, monetarySecReportData);
  

  return (
    <Fragment>
      <ErrorModal
        visible={deleteInfo.modalVisible}
        onCancel={() =>
          setDeleteInfo({
            modalVisible: false,
            errorMsg: "",
          })
        }
        onOk={handleDeleteLevel}
        msg={deleteInfo.errorMsg}
      />
      {monetaryReportData?.length > 0
        ? monetaryReportData?.map((v) => (
            <div key={v.key} className={styles.monetaryBox}>
              <FlexDiv
                style={{ borderBottom: "1px solid #e4e4e4", paddingBottom: 8 }}
              >
                <div style={{ display: "inline-flex", alignItems: "center" }}>
                  <LittleTitle mr="4px" mt="0px" title="一级类别" />
                  <Input
                    placeholder="请输入一级分类名"
                    className={cn(
                      styles.monetaryInput,
                      (repeatFirName?.includes(v.oneLevelCategory) ||
                        requiredFir?.includes(v.key)) &&
                        "form_error"
                    )}
                    style={{ width: 236, marginLeft: 8 }}
                    maxLength={50}
                    onChange={(e) =>
                      handleSaveParams(v.key, "", e.target.value)
                    }
                    value={v.oneLevelCategory}
                  />
                  {repeatFirName?.includes(v.oneLevelCategory) && (
                    <span className={styles.errormsg}>
                      该一级类别名称已有记录，不能重复，请确认！
                    </span>
                  )}
                </div>
                <div
                  style={{
                    display: "inline-flex",
                    position: "relative",
                    bottom: "-5px",
                  }}
                >
                  <ButtonNoBorder
                    text="添加二级类别"
                    src={icon_plus}
                    onClick={() => handleAddSecLevel(v.key)}
                  />
                  <VerticleBar style={{ top: "14px" }} />
                  <TableOptBtn
                    img={icon_delete}
                    style={{ lineHeight: "26px" }}
                    text="删除"
                    onClick={() => {
                      setDeleteInfo({
                        modalVisible: true,
                        errorMsg: "确认要删除该一级分类？",
                        firKey: v.key,
                      });
                    }}
                  />
                </div>
              </FlexDiv>
              {monetarySecReportData[v.key] &&
              monetarySecReportData[v.key].length > 0
                ? monetarySecReportData[v.key]?.map((m) => (
                    <MoSecEditorText
                      editType={m.key}
                      firKey={v.key}
                      editContent={m.content}
                      twoLevelCategory={m.twoLevelCategory}
                      height={150}
                      callback={handleSaveParams}
                      setDeleteInfo={setDeleteInfo}
                      repeatSecName={repeatSecName}
                    />
                  ))
                : null}
            </div>
          ))
        : null}
      <div className={styles.addBtn}>
        <span className={styles.addBtn_line}></span>
        <ButtonNoBorder onClick={handleAddFirLevel} text="点击添加一级分类" />
      </div>
    </Fragment>
  );
};

export default MonetaryEditorText;
